from DrissionPage import ChromiumPage
import time

def setup_script():
    script = """
    document.addEventListener('mousemove', function(event) {
        if (event.target !== lastElement) {
            lastElement = event.target;
            var path = getElementXPath(event.target);
            console.log('Hovered XPath:', path);
            window.hoveredXPath = path;
        }
    });

    function getElementXPath(elt) {
        var path = "";
        for (; elt && elt.nodeType == 1; elt = elt.parentNode) {
            var idx = getElementIdx(elt);
            var xname = elt.tagName;
            if (idx > 1) xname += "[" + idx + "]";
            path = "/" + xname + path;
        }
        return path;
    }

    function getElementIdx(elt) {
        var count = 1;
        for (var sib = elt.previousSibling; sib; sib = sib.previousSibling) {
            if (sib.nodeType == 1 && sib.tagName == elt.tagName) count++;
        }
        return count;
    }

    var lastElement = null;
    """
    return script

def get_hovered_xpath(driver):
    script = "return window.hoveredXPath;"
    return driver.run_js(script)

# 使用Chrome浏览器
driver = ChromiumPage()

# 导航到目标网页
driver.get("https://www.bilibili.com/")

# 设置监听脚本
driver.run_js(setup_script())

# 循环获取鼠标悬停的元素的XPath
try:
    while True:
        time.sleep(1)  # 每秒获取一次
        hovered_xpath = get_hovered_xpath(driver)
        if hovered_xpath:
            print(f"Hovered XPath: {hovered_xpath}")
except KeyboardInterrupt:
    pass
finally:
    driver.quit()
